#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证conversation_search修复后的功能
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.database.manager import DatabaseManager
from src.core.conversation_manager import ConversationManager
from src.config import load_config

async def verify_conversation_search():
    """验证conversation_search功能"""
    print("=== 验证conversation_search修复 ===")
    
    try:
        # 1. 初始化数据库管理器
        print("\n1. 初始化数据库连接...")
        config = load_config()
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        
        # 2. 初始化对话管理器
        print("2. 初始化对话管理器...")
        conversation_manager = ConversationManager(db_manager, config)
        await conversation_manager.initialize()
        
        # 3. 检查ChromaDB连接状态
        print("3. 检查ChromaDB连接状态...")
        chromadb_ping = await db_manager.chromadb_client.ping()
        print(f"   ChromaDB连接状态: {'✅ 正常' if chromadb_ping else '❌ 异常'}")
        
        # 4. 检查ChromaDB集合统计
        print("4. 检查ChromaDB集合统计...")
        collections = ['memories', 'documents', 'conversations']
        for collection_name in collections:
            try:
                stats = await db_manager.chromadb_client.get_collection_stats(collection_name)
                count = stats.get('count', 0)
                print(f"   {collection_name}: {count} 条记录")
            except Exception as e:
                print(f"   {collection_name}: 获取统计失败 - {e}")
        
        # 5. 检查MongoDB对话数据
        print("5. 检查MongoDB对话数据...")
        try:
            # 获取一个示例对话
            conversations_collection = db_manager.mongodb_client.get_collection('conversations')
            sample_conv = await conversations_collection.find_one({})
            if sample_conv:
                print(f"   MongoDB中有对话数据，示例conversation_id: {sample_conv.get('conversation_id', 'N/A')}")
            else:
                print("   ❌ MongoDB中没有对话数据")
        except Exception as e:
            print(f"   检查MongoDB对话数据失败: {e}")
        
        # 6. 测试conversation_search功能
        print("\n6. 测试conversation_search功能...")
        test_queries = ["测试", "游戏", "hello"]
        
        for query in test_queries:
            print(f"\n   查询: '{query}'")
            try:
                results = await conversation_manager.search_conversations(
                    query=query,
                    user_id="default_user",
                    limit=3
                )
                
                if results:
                    print(f"   ✅ 找到 {len(results)} 个结果:")
                    for i, result in enumerate(results, 1):
                        conv_id = result.get('conversation_id', 'N/A')
                        title = result.get('title', 'N/A')
                        similarity = result.get('similarity', 0)
                        print(f"     {i}. ID: {conv_id}")
                        print(f"        标题: {title}")
                        print(f"        相似度: {similarity:.3f}")
                else:
                    print(f"   ❌ 未找到相关对话")
                    
            except Exception as e:
                print(f"   ❌ 搜索失败: {e}")
                import traceback
                traceback.print_exc()
        
        # 7. 测试直接ChromaDB搜索
        print("\n7. 测试直接ChromaDB搜索...")
        try:
            search_results = await db_manager.chromadb_client.search_conversations(
                query="测试",
                limit=3
            )
            
            if search_results:
                print(f"   ✅ ChromaDB直接搜索找到 {len(search_results)} 个结果:")
                for i, result in enumerate(search_results, 1):
                    conv_id = result.get('conversation_id', 'N/A')
                    content = result.get('content', 'N/A')[:50] + '...' if len(result.get('content', '')) > 50 else result.get('content', 'N/A')
                    similarity = result.get('similarity', 0)
                    print(f"     {i}. conversation_id: {conv_id}")
                    print(f"        内容: {content}")
                    print(f"        相似度: {similarity:.3f}")
            else:
                print(f"   ❌ ChromaDB直接搜索未找到结果")
                
        except Exception as e:
            print(f"   ❌ ChromaDB直接搜索失败: {e}")
        
        # 8. 关闭连接
        print("\n8. 关闭数据库连接...")
        await db_manager.close()
        
        print("\n=== 验证完成 ===")
        
    except Exception as e:
        print(f"\n💥 验证过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    asyncio.run(verify_conversation_search())